package com.jinlia.show.modules.wxapp.service;

import com.jinlia.show.common.core.exception.MyRuntimeException;
import com.jinlia.show.common.core.utils.UserInfoUtils;
import com.jinlia.show.modules.base.constant.*;
import com.jinlia.show.modules.base.model.form.OrderForm;
import com.jinlia.show.modules.base.model.po.DeliveryOrderPO;
import com.jinlia.show.modules.base.model.po.OrderPO;
import com.jinlia.show.modules.base.model.po.PayOrderPO;
import com.jinlia.show.modules.base.system.entity.DeliveryOrder;
import com.jinlia.show.modules.base.system.entity.Order;
import com.jinlia.show.modules.base.system.entity.OrderItem;
import com.jinlia.show.modules.base.system.service.DeliveryOrderMapperService;
import com.jinlia.show.modules.base.system.service.MemberCardMapperService;
import com.jinlia.show.modules.base.system.service.OrderItemMapperService;
import com.jinlia.show.modules.base.system.service.OrderMapperService;
import com.jinlia.show.modules.base.utils.OrderNumGenerator;
import com.jinlia.show.modules.base.utils.PayOrderNumGenerator;
import com.jinlia.show.modules.base.wxapp.entity.PayOrder;
import com.jinlia.show.modules.base.wxapp.entity.ShoppingCart;
import com.jinlia.show.modules.base.wxapp.entity.UserCouponRel;
import com.jinlia.show.modules.base.wxapp.service.*;
import com.jinlia.show.modules.wxapp.model.form.NewOrderForm;
import com.jinlia.show.modules.wxapp.model.vo.OrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class OrderService {
    @Autowired
    private OrderMapperService orderMapperService;
    @Autowired
    private OrderItemMapperService orderItemMapperService;
    @Autowired
    private DeliveryOrderMapperService deliveryOrderMapperService;
    @Autowired
    private MemberCardMapperService memberCardMapperService;
    @Autowired
    private ShoppingCartMapperService shoppingCartMapperService;
    @Autowired
    private PayOrderMapperService payOrderMapperService;
    @Autowired
    private UserCouponRelMapperService userCouponRelMapperService;
    @Autowired
    private PayOrderNumGenerator payOrderNumGenerator;
    @Autowired
    OrderNumGenerator orderNumGenerator;
    /**
     * 取消订单
     *
     * @param id
     * @return
     */
    @Transactional
    public Boolean cancel(Long id) {
        Order byId = orderMapperService.getById(id);
        if (!OrderPayStatusEnum.UN_PAY.getValue().equals(byId.getPayStatus())) {
            throw new MyRuntimeException("非待支付的状态不可取消!!!");
        }
        orderMapperService.removeById(byId.getId());
        orderItemMapperService.lambdaUpdate()
                .eq(OrderItem::getOrderId, id)
                .remove();
        payOrderMapperService.lambdaUpdate()
                .eq(PayOrder::getPayForId, id)
                .eq(PayOrder::getPayForType, PayForTypeEnum.SALE.getValue())
                .remove();
        deliveryOrderMapperService.lambdaUpdate()
                .eq(DeliveryOrder::getOrderId, id)
                .remove();
        return Boolean.TRUE;
    }


    @Transactional
    public Boolean confirmReceive(Long id) {
        //返显订单状态
        DeliveryOrder one = deliveryOrderMapperService.lambdaQuery().eq(DeliveryOrder::getOrderId, id).one();
//        deliveryOrderMapperService.userConfirmDeliveryOrder(one);
        return Boolean.TRUE;
    }

    public OrderVO getOrderVO(Long id) {
        List<OrderPO> poByIds = orderMapperService.getPOByIds(id);
        OrderPO orderPO = poByIds.get(0);
        DeliveryOrder one = deliveryOrderMapperService.lambdaQuery().eq(DeliveryOrder::getOrderId, id).one();
        orderPO.setDeliveryOrder(one);
        return OrderVO.fromObject(orderPO);
    }

    public Map<String, String> myOrderBoard() {
        List<Order> list = orderMapperService.lambdaQuery()
                .eq(Order::getUserId, UserInfoUtils.getUserId())
                .list();
        HashMap<String, String> returnMap = new HashMap<>();
        long count = list.stream().filter(i -> OrderPayStatusEnum.UN_PAY.getValue() == i.getPayStatus()).count();
        returnMap.put("UN_PAY", String.valueOf(count)); //DeliveryOrderStatusEnum
        return returnMap;
    }

    /**
     * 新增订单:返回付款单
     *
     * @param orderForm
     * @return
     */
    @Transactional
    public PayOrderPO addByShoppingCar(OrderForm orderForm) {
        /**
         * 校验购物车是否已被下单
         */
        List<ShoppingCart> listShoppingCart = shoppingCartMapperService.lambdaQuery()
                .in(ShoppingCart::getId, orderForm.getShoppingCartIds())
                .list();
        if (CollectionUtils.isEmpty(listShoppingCart)) {
            throw new MyRuntimeException("购物车已被下单!!!");
        }
        //
        //生成订单
        Order order = orderMapperService.orderByShoppingCar(orderForm);//生成销售单
        order.setOrderNum(orderNumGenerator.nextId());
        orderMapperService.save(order);
        orderItemMapperService.createOrderItemByCarIds(listShoppingCart, order); //生成销售单详情
        /**
         * 新增付款单
         */
        PayOrder payOrder = payOrderMapperService.createByOrder(order);
        payOrder.setPayOrderNum(payOrderNumGenerator.nextId());
        payOrderMapperService.save(payOrder);
        PayOrderPO payOrderPO = PayOrderPO.fromEntity(payOrder);
        payOrderPO.setPayForEntity(order);
        /**
         * 新增配送单
         */
        DeliveryOrderPO deliveryOrder = orderForm.getDeliveryOrder();
        if (Objects.nonNull(deliveryOrder) && !DeliveryTypeEnum.SELF_PICT.getValue().equals(order.getDeliveryType())) {
            deliveryOrder.setId(null);//id
            deliveryOrder.setOrderId(order.getId());//回显订单号
            deliveryOrder.setCurrentErrandStatus(0);
            deliveryOrder.setDeliveryStatus(DeliveryStatusEnum.A.getValue());
            deliveryOrder.setEnableStatus(EnableStatusEnum.ENABLE.getValue());
            deliveryOrderMapperService.add(deliveryOrder);
        }
        /****
         * 优惠券处理
         */
        if (!CollectionUtils.isEmpty(orderForm.getCouponRelIds())) {
            List<UserCouponRel> list = userCouponRelMapperService.lambdaQuery()
                    .in(UserCouponRel::getId, orderForm.getCouponRelIds())
                    .list();
            //校验状态
            list.forEach(i -> {
            });
            userCouponRelMapperService.lambdaUpdate()
                    .in(UserCouponRel::getId, orderForm.getCouponRelIds())
                    .set(UserCouponRel::getUsedTime, LocalDateTime.now())
                    .update();
        }

        //更新购物车的状态=>删除
        shoppingCartMapperService.lambdaUpdate()
                .set(ShoppingCart::getEnableStatus, EnableStatusEnum.DISABLE.getValue())
                .in(ShoppingCart::getId, orderForm.getShoppingCartIds())
                .remove();
        return payOrderPO;
    }

    /**
     * 更新订单
     *
     * @param orderPO
     * @return
     */
    public void updateOrder(OrderPO orderPO) {
        //修改订单备注
        orderMapperService.lambdaUpdate()
                .eq(Order::getId, orderPO.getId())
                .set(Order::getRemark, orderPO.getRemark())
                .update(new Order());
        //配送单信息
        DeliveryOrder deliveryOrder = orderPO.getDeliveryOrder();
        this.deliveryOrderMapperService.lambdaUpdate()
                .eq(DeliveryOrder::getId, deliveryOrder.getId())
                .set(DeliveryOrder::getDeliveryAddress, deliveryOrder.getDeliveryAddress())
                .set(DeliveryOrder::getDeliveryAddressLatitude, deliveryOrder.getDeliveryAddressLatitude())
                .set(DeliveryOrder::getDeliveryAddressLongitude, deliveryOrder.getDeliveryAddressLongitude())
                .set(DeliveryOrder::getDeliveryAddressTitle, deliveryOrder.getDeliveryAddressTitle())
                .update(new DeliveryOrder());
    }

    public PayOrder newOrder(NewOrderForm orderForm) {
        //新增订单
        Order newOrder = orderMapperService.initOrder(orderForm);
        newOrder.setOrderNum(orderNumGenerator.nextId());
        orderMapperService.save(newOrder);
        //新增订单详情
        orderForm.getOrderItems().forEach(i -> {
            i.setOrderId(newOrder.getId());
            orderItemMapperService.save(i);
        });
        //处理配送单
        DeliveryOrder deliveryOrder = orderForm.getDeliveryOrder();
        if (Objects.nonNull(deliveryOrder) && !DeliveryTypeEnum.SELF_PICT.getValue().equals(newOrder.getDeliveryType())) {
            deliveryOrder.setOrderId(newOrder.getId());
            deliveryOrder.setCurrentErrandStatus(0);
            deliveryOrder.setDeliveryStatus(DeliveryStatusEnum.A.getValue());
            deliveryOrderMapperService.save(deliveryOrder);
        }
        //处理优惠券
        List<UserCouponRel> userCouponRelList = orderForm.getCouponList();
        if (!CollectionUtils.isEmpty(userCouponRelList)) {
            userCouponRelList.forEach(i -> {
                i.setUserId(UserInfoUtils.getUserId());
                i.setUsedTime(LocalDateTime.now());
            });
            userCouponRelMapperService.saveBatch(userCouponRelList);
        }
        //生产支付单
        PayOrder payOrder = payOrderMapperService.createByOrder(newOrder);
        payOrder.setPayOrderNum(payOrderNumGenerator.nextId());
        payOrderMapperService.save(payOrder);
        return payOrder;
    }
}
